package cn.sheep.dolphin.common

import org.apache.spark.sql.Row

/**
  * 计算离线报表的业务逻辑
  * author: old sheep
  * QQ: 64341393 
  * Created 2018/11/29
  */
object DolphinKpi {

	/**
	  * 整理判断业务指标数据
	  *
	  * @param row
	  * @return
	  */
	def caculateKpi(row: Row): List[Double] = {

		// 提取判断的字段依据
		val requestMode = row.getAs[Int]("requestmode")
		val processNode = row.getAs[Int]("processnode")
		val effective = row.getAs[Int]("iseffective")
		val billing = row.getAs[Int]("isbilling")
		val isBid = row.getAs[Int]("isbid")
		val isWin = row.getAs[Int]("iswin")
		val adOrderId = row.getAs[Int]("adorderid")


		// (原始请求, 有效请求, 广告请求)
		val (rawRequest, effectiveRequest, adRequest) = if (requestMode == 1 && processNode == 3) (1, 1, 1)
		else if (requestMode == 1 && processNode == 2) (1, 1, 0)
		else if (requestMode == 1 && processNode == 1) (1, 0, 0)
		else (0, 0, 0)

		// 是参与竞价的日志
		val isRTB = if (effective == 1 && billing == 1 && isBid == 1 && adOrderId != 0) 1 else 0
		// 是竞价成功的日志吗
		val (succRTB, expense, cost) = if (effective == 1 && billing == 1 && isWin == 1) {
			val winPrice = row.getAs[Double]("winprice") / 1000d
			val adPayment = row.getAs[Double]("adpayment") / 1000d
			(1, winPrice, adPayment)
		} else (0, 0d, 0d)


		// (广告的展示, 广告的点击)
		val (adShow, adClick) = if (requestMode == 2 && effective == 1) (1, 0)
		else if (requestMode == 3 && effective == 1) (0, 1)
		else (0, 0)

		// 组装数据格式(原始请求,有效请求,广告请求,参与竞价,竞价成功,广告展示,广告点击,广告消费,广告成本))
		List(rawRequest, effectiveRequest, adRequest, isRTB, succRTB, adShow, adClick, expense, cost)
	}

}
